#include <iostream>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <memory>
#include "log.hpp"
#include "InetAddr.hpp"
#include "Tcp_sever.hpp"
void Usage(char *str)
{
    std::cout << "Usage:\n\t" << str << "lock_port\n"
              << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }
    // tcp client 要bind，不要显示的bind，
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    int n = connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n < 0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(3);
    }
    while(true)
    {
        std::cout<<"Please Enter# ";
        std::string outstring;
        std::getline(std::cin,outstring);
        std::cout<<"2"<<std::endl;
        ssize_t s = send(sockfd,outstring.c_str(),outstring.size(),0);//write
        std::cout<<"2"<<std::endl;
        if(s > 0)//发送成功
        {
            char inbuffer[1024];
            ssize_t m = recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);
            if(m > 0)//接受成功
            {
                std::cout<<"2"<<std::endl;
                inbuffer[m] = 0;
                std::cout<<inbuffer<<std::endl;
            }
            else
            {
                std::cout<<"0"<<std::endl;

                break;
            }
        }
        else
        {
            break;
            std::cout<<"0"<<std::endl;
        }

    }
    ::close(sockfd);
    return 0;
}